package com.begye.smartloan.apptest.homeadsource

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.ext.toThousandUnitFormat
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.doPostRequest
import org.json.JSONArray
import org.json.JSONObject

class HomeAdSourceViewModel : ViewModel() {

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _homeDetailLiveData = MutableLiveData<JSONObject>()
    val onHomeDetailLiveData get() = _homeDetailLiveData

    fun requestHomeDetail() {
        doPostRequest(
            path = "/xYmPrpxwTGlchReo4ijJw",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        val currency = obj.optString("currency", "")
                        val limit = obj.optJSONArray("limit") ?: JSONArray()
                        if (limit.length() > 0) {
                            val first = limit.optJSONObject(0)
                            val item = JSONObject(first.toString()).apply {
                                put("currency", currency)
                                put("amount", first.optString("amount", "").toThousandUnitFormat())
                                put(
                                    "increasedAmount1",
                                    first.optString("increasedAmount1", "").toThousandUnitFormat()
                                )
                                put(
                                    "increasedAmount2",
                                    first.optString("increasedAmount2", "").toThousandUnitFormat()
                                )
                            }
                            _homeDetailLiveData.value = item
                        }

                    } catch (e: Exception) {
                        //
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }
}